package Eclass.Schedule;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import login.LoginForm;
import login.UserModel;

import notification.LogNotifModel;
import notification.NotifManager;

import org.apache.poi.hssf.record.ScenarioProtectRecord;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import Candidate.CandidateForm;
import Candidate.CandidateModel;
import Eclass.EclassForm;
import Eclass.BatchClass.BatchClassManager;
import Eclass.Exam.ExamManager;
import Eclass.Score.ScoreForm;
import Filesharing.FileManager;
import Filesharing.FileModel;
import Forum.ForumThreadForm;
import Master.SchoolForm;
import OpenFile.OpenFile;

public class ScheduleAction extends Action{
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		ScheduleForm scheduleForm = (ScheduleForm) form;
		ScheduleManager scheduleManager = new ScheduleManager();
		FileManager filesharingManager = new FileManager();
		HttpSession session = request.getSession(true);
		Boolean isResetPage = true;
		
		//---------------------- Navigation -----------------------------
				CandidateForm candidateForm = new CandidateForm();
				SchoolForm schoolForm = new SchoolForm();
				EclassForm eClassForm = new EclassForm();
				ForumThreadForm forumForm = new ForumThreadForm();
				ScoreForm scoreForm = new ScoreForm();
				LoginForm logForm = new LoginForm();
				
				//candidate
				if("updateCandidate".equalsIgnoreCase(scheduleForm.getTask())) {
					candidateForm.getcModel().setRegisNo("01-13-12- 029");
					candidateForm.setTask("update");
					return mapping.findForward("candidate");
				}else if("manageTrainee".equalsIgnoreCase(scheduleForm.getTask())) {	
					candidateForm.setTask("manageTrainee");
					return mapping.findForward("candidate");
				}else if("accountSetting".equalsIgnoreCase(scheduleForm.getTask())) {	
					candidateForm.setTask("accountSetting");
					return mapping.findForward("candidate");
				}else if("profileSetting".equalsIgnoreCase(scheduleForm.getTask())) {	
					candidateForm.setTask("profileSetting");
					return mapping.findForward("candidate");
				}else

				//eclass
				if("batch".equalsIgnoreCase(scheduleForm.getTask())) {
					eClassForm.setTask("batch");
					return mapping.findForward("eclass");
				}else if("listExamPrep".equalsIgnoreCase(scheduleForm.getTask())){
					eClassForm.setTask("listExamPrep");
					return mapping.findForward("eclass");
				}else 
				
				//master
				if("manageSchool".equalsIgnoreCase(scheduleForm.getTask())) {
					schoolForm.setTask("manageSchool");
					return mapping.findForward("master");
		  		}else if("manageJob".equalsIgnoreCase(scheduleForm.getTask())) {
					schoolForm.setTask("manageJob");
					return mapping.findForward("master");
		  		}else if("manageGroupClass".equalsIgnoreCase(scheduleForm.getTask())) {
					schoolForm.setTask("manageGroupClass");
					return mapping.findForward("master");
		  		}else 

				//forum
				if("forumPage".equalsIgnoreCase(scheduleForm.getTask())) {
					forumForm.setTask("forumPage");
					return mapping.findForward("forum");
				}else 
				
				//score
				if("report".equalsIgnoreCase(scheduleForm.getTask())) {
					scoreForm.setTask("report");
					return mapping.findForward("score");
				}else 

				//login
				if("showNotification".equalsIgnoreCase(scheduleForm.getTask())) {
					logForm.setTask("showNotification");
					return mapping.findForward("login");
				}
		//-------------------------------------------------------------------
		
		//utk dapetin usermodel dr session (update/delete file)
		UserModel user = (UserModel)session.getAttribute("userLogin");
		
		//utk dapetin scheduleForm berdasarkan Notification
		ScheduleForm schNotifForm = (ScheduleForm) session.getAttribute("showScheduleFromNotif");
		session.removeAttribute("showScheduleFromNotif");
		if( schNotifForm !=null && schNotifForm.getTask()!=null && "listSchedule".equalsIgnoreCase(schNotifForm.getTask()) ){
			scheduleForm.setTask(schNotifForm.getTask());
			scheduleForm.setSelectedBatchId(schNotifForm.getSelectedBatchId());
			Integer batchId = null;
			try{
				BatchClassManager bcm = new BatchClassManager();
				batchId = bcm.getBatchClassById(scheduleForm.getSelectedBatchId()).getBatchId();
				scheduleForm.setSelectedBatchId(batchId);
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
		}
		
		/*if(request.getParameter("task")!=null && "showSchedule".equalsIgnoreCase(request.getParameter("task").toString()) && request.getParameter("batchClassId")!=null){
			scheduleForm.setTask("listSchedule");
			Integer batchId = null;
			try{
				BatchClassManager bcm = new BatchClassManager();
				batchId = bcm.getBatchClassById(Integer.parseInt(request.getParameter("batchClassId").toString())).getBatchId();
				scheduleForm.setSelectedBatchId(batchId);
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
		}*/
		
		
		
		if("openFile".equalsIgnoreCase(scheduleForm.getTask())) {
			OpenFile op = new OpenFile();
			String directoryPath = "tesUploadSubject/";
			String filePath = getServlet().getServletContext().getRealPath("/") + directoryPath;
			filePath += scheduleForm.getPathOpenFile();
			op.openFile(filePath);
			isResetPage = false;
			//scheduleForm.setTask(null);
		}
		if ("listSchedule".equalsIgnoreCase(scheduleForm.getTask())) {
			scheduleForm.setListBatch(scheduleManager.getBatch());
			//scheduleForm.setSelectedBatchId(((CandidateModel)(scheduleForm.getListBatch().get(0))).getBatchId());
			scheduleForm.setCurrentPage(1);
			setListSchedule(scheduleForm, scheduleManager, filesharingManager, user, request);
			//scheduleForm.setTotalPage(scheduleForm.getListSchedule().size());
			return mapping.findForward("listSchedule");
		} 
		if ("backToListSchedule".equalsIgnoreCase(scheduleForm.getTask())) {
			scheduleForm.setListBatch(scheduleManager.getBatch());
			//scheduleForm.setSelectedBatchId(((CandidateModel)(scheduleForm.getListBatch().get(0))).getBatchId());
			scheduleForm.setCurrentPage(1);
			setListSchedule(scheduleForm, scheduleManager, filesharingManager, user, request);
			//scheduleForm.setTotalPage(scheduleForm.getListSchedule().size());
			return mapping.findForward("listSchedule");
		} else if ("goto".equalsIgnoreCase(scheduleForm.getTask())) {
			setListSchedule(scheduleForm, scheduleManager, filesharingManager, user, request);
			//scheduleForm.setTotalPage(scheduleForm.getListSchedule().size());
			scheduleForm.setListBatch(scheduleManager.getBatch());	
			return mapping.findForward("listSchedule");
		} 
		if ("insertFileSubject".equalsIgnoreCase(scheduleForm.getTask())) {
			String title = "Upload File Subject";
			scheduleForm.setTask("uploadFileSubject");
			request.setAttribute("title",title);
			scheduleForm.getModelFileSch().setFileName(null);
			return mapping.findForward("insertFileSubject");
		}
		if ("uploadFileSubject".equalsIgnoreCase(scheduleForm.getTask())) {
			if (scheduleForm.getModelFileSch().getDescription() == null || scheduleForm.getModelFileSch().getDescription().equalsIgnoreCase("")) {
				scheduleForm.getModelFileSch().setDescription(scheduleForm.getModelSchedule().getSubjectTitle());
			}
			
			// Process the FormFile
			FormFile myFile = scheduleForm.getTheFile();
			String contentType = myFile.getContentType();
			
			//Get the file name
			String fileName  = myFile.getFileName();
			
			//int fileSize = myFile.getFileSize();
			byte[] fileData  = myFile.getFileData();
			
			//Get the servers upload directory real path name
			String directoryPath = "tesUploadSubject/";
			scheduleForm.getModelFileSch().setFilePath(directoryPath);
			scheduleForm.getModelFileSch().setUploaderId(user.getUserid());
			String filePath = getServlet().getServletContext().getRealPath("/") +directoryPath;
			
			if(myFile.getFileSize() <= 5000000) {
				/* Save file on the server */
				if(!fileName.equals("")){  
					//Create file
					File fileToCreate = new File(filePath, fileName);
					  
					//If file does not exists create file  
					if(!fileToCreate.exists()){
						FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
						fileOutStream.write(myFile.getFileData());
						fileOutStream.flush();
						fileOutStream.close();
						filesharingManager.addFileSch(scheduleForm.getModelFileSch());
						
						insertNotificationMateri("insert", scheduleForm.getModelFileSch(), user, scheduleForm.getModelSchedule().getSubjectTitle(), scheduleForm.getSelectedBatchId());
					} else {
						Integer curFileId = filesharingManager.getCurFileId();
						
						String oldFileName = fileName.substring(0,fileName.lastIndexOf("."));
						String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
						String newFileName = oldFileName + " - " + curFileId + fileType;
					
					    // File (or directory) with new name
					    File file2 = new File(filePath, newFileName);
					    /*if(file2.exists()) throw new java.io.IOException("file exists");*/

					    // Rename file (or directory)
					    boolean success = fileToCreate.renameTo(file2);
					    if (!success) {
					        // File was not successfully renamed
					    	System.out.println("File was not successfully renamed");
					    	session.setAttribute("result", "File was not successfully renamed");
					    } else {
					    	FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
							fileOutStream.write(myFile.getFileData());
							fileOutStream.flush();
							fileOutStream.close();
							scheduleForm.getModelFileSch().setFileName(newFileName);
							filesharingManager.addFileSch(scheduleForm.getModelFileSch());
						}
					}
				}
				
				String fullFilePath = filePath+fileName;
				  
				//Set file name to the request object
				request.setAttribute("directoryPath",directoryPath);
				request.setAttribute("fileName",fileName);
				
				//utk notification crud
				session.setAttribute("result", "Upload File Subject success");
				isResetPage = false;
				
				//scheduleForm.setListBatch(scheduleManager.getBatch());	
				//scheduleForm.setSelectedBatchId((Integer)scheduleForm.getListBatch().get(0));
				
				//setListSchedule(scheduleForm, scheduleManager, filesharingManager, user, request);
				//scheduleForm.getModelFileSch().setFileName(null);
				//return mapping.findForward("listSchedule");
			}
		}
		if ("updateFileSubject".equalsIgnoreCase(scheduleForm.getTask())) {
			String title = "Update File Subject";
			
			//untuk ngeset model bwt update
			scheduleForm.setModelFileSch(filesharingManager.selectFile(scheduleForm.getModelFileSch().getFileId()));
			scheduleForm.setTask("editFileSubject");
			request.setAttribute("title",title);
			return mapping.findForward("insertFileSubject");
		}
		if ("editFileSubject".equalsIgnoreCase(scheduleForm.getTask())) {
			if (scheduleForm.getModelFileSch().getDescription() == null || scheduleForm.getModelFileSch().getDescription().equalsIgnoreCase("")) {
				scheduleForm.getModelFileSch().setDescription(scheduleForm.getModelSchedule().getSubjectTitle());
			}
									  
			//Utk Query Update
			FileModel fmNewFile = scheduleForm.getModelFileSch();
			if(fmNewFile.getFileName()!=null && !fmNewFile.getFileName().equalsIgnoreCase("")) {
				
				// Process the FormFile
				FormFile myFile = scheduleForm.getTheFile();
				String contentType = myFile.getContentType();
				  
				//Get the file name
				String fileName  = myFile.getFileName();
				
				//int fileSize = myFile.getFileSize();
				byte[] fileData  = myFile.getFileData();
				  
				//Get the servers upload directory real path name
				String directoryPath = "tesUploadSubject/";
				scheduleForm.getModelFileSch().setFilePath(directoryPath);
				scheduleForm.getModelFileSch().setUploaderId(user.getUserid());
				String filePath = getServlet().getServletContext().getRealPath("/") +directoryPath;
				  
				//ngambil id file yg lama (yg mau direplace) -> DB
				scheduleForm.setModelFileSch(filesharingManager.selectFile(scheduleForm.getModelFileSch().getFileId()));
				//delete file dari folder
				directoryPath = scheduleForm.getModelFileSch().getFilePath();
				filePath = getServlet().getServletContext().getRealPath("/") +directoryPath +scheduleForm.getModelFileSch().getFileName();
					
				File myFile2 = new File(filePath);
				if (!myFile2.isDirectory()) {
					myFile2.delete();
				}
				  				  
				//mulai proses update file ke folder
				fileName = fmNewFile.getFileName();
				filePath = fmNewFile.getFilePath();
				  
				filePath = getServlet().getServletContext().getRealPath("/") +filePath;
				
				if(myFile.getFileSize() <= 5000000) {
					//Save file on the server 
					if(!fileName.equals("")){  
						//Create file
						File fileToCreate = new File(filePath, fileName);
						
						//If file does not exists create file  
						if(!fileToCreate.exists()){
							FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
							fileOutStream.write(myFile.getFileData());
							fileOutStream.flush();
							fileOutStream.close();
							filesharingManager.updateFileSch(fmNewFile);
							insertNotificationMateri("update", scheduleForm.getModelFileSch(), user, scheduleForm.getModelSchedule().getSubjectTitle(),scheduleForm.getModelSchedule().getBatchClassId());
							
						} else {
							String selectedFileId = scheduleForm.getModelFileSch().getFileId();
							
							String oldFileName = fileName.substring(0,fileName.lastIndexOf("."));
							String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
							String newFileName = oldFileName + " - " + selectedFileId + fileType;
						
						    // File (or directory) with new name
						    File file2 = new File(filePath, newFileName);
						    /*if(file2.exists()) throw new java.io.IOException("file exists");*/

						    // Rename file (or directory)
						    boolean success = fileToCreate.renameTo(file2);
						    if (!success) {
						        // File was not successfully renamed
						    	System.out.println("File was not successfully renamed");
						    	session.setAttribute("result", "File was not successfully renamed");
						    } else {
						    	FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
								fileOutStream.write(myFile.getFileData());
								fileOutStream.flush();
								fileOutStream.close();
								fmNewFile.setFileName(newFileName);
								filesharingManager.updateFileSch(fmNewFile);
								insertNotificationMateri("update", scheduleForm.getModelFileSch(), user, scheduleForm.getModelSchedule().getSubjectTitle(), scheduleForm.getSelectedBatchId());
								
								/*filesharingManager.addFileSch(scheduleForm.getModelFileSch());*/
							}
						}
					}
					  
					String fullFilePath = filePath+fileName;
					  
					//Set file name to the request object
					request.setAttribute("directoryPath",directoryPath);
					request.setAttribute("fileName",fileName);
								
			    }
				  
					//utk notification crud
					session.setAttribute("result", "Update File Subject success");
					
					//setListSchedule(scheduleForm, scheduleManager, filesharingManager, user, request);
				  	isResetPage = false;
				  	//fileShareForm.getModelFile().setFileName(null);
				  	//return mapping.findForward("listSchedule");
			}
		}
		if ("deleteFileSubject".equalsIgnoreCase(scheduleForm.getTask())) {	
			if (!scheduleForm.getModelFileSch().getFileId().equalsIgnoreCase("0")) {
				scheduleForm.setModelFileSch(filesharingManager.selectFile(scheduleForm.getModelFileSch().getFileId()));
				String directoryPath = scheduleForm.getModelFileSch().getFilePath();
				String filePath = getServlet().getServletContext().getRealPath("/") +directoryPath +scheduleForm.getModelFileSch().getFileName();
				
				File myFile = new File(filePath);
				if (!myFile.isDirectory()) {
					myFile.delete();
				}
				
				filesharingManager.deleteFile(scheduleForm.getModelFileSch().getFileId());
			}
			
			//utk notification crud
			session.setAttribute("result", "Delete File Subject success");
			
			isResetPage = false;
			//fileShareForm.getModelFile().setFileName(null);
			//setListSchedule(scheduleForm, scheduleManager, filesharingManager, user, request);
			//return mapping.findForward("listSchedule");
		}
		
		scheduleForm.setListBatch(scheduleManager.getBatch());	
		
		if(isResetPage){
			scheduleForm.setSelectedBatchId(((CandidateModel)(scheduleForm.getListBatch().get(0))).getBatchId());
			scheduleForm.setCurrentPage(1);
		}
		setListSchedule(scheduleForm, scheduleManager, filesharingManager, user, request);
		
		//scheduleForm.setTask(null);
		return mapping.findForward("listSchedule");
	}
	
	private Boolean insertNotificationMateri(String tipe,FileModel fm,UserModel user, String subjectTitle, Integer batchClassId) {
		
		LogNotifModel lgm = new LogNotifModel();
		lgm.setUserId(fm.getUploaderId());
		if("insert".equalsIgnoreCase(tipe))
			lgm.setDescription(fm.getUploaderId().toUpperCase() + " add "+fm.getFileName()+" @ Subject "+subjectTitle);
		else if("update".equalsIgnoreCase(tipe))
			lgm.setDescription(fm.getUploaderId().toUpperCase() + " update "+fm.getFileName()+" @ Subject "+subjectTitle);
		lgm.setLink("/WebFinalProject/Schedule.do?task=showSchedule&batchClassId="+batchClassId);
		lgm.setBatchClassId(fm.getBatchClassId());
		NotifManager notifMgr = new NotifManager();
		Boolean cek = false;
		String role = user.getRole();
		if(notifMgr.insertLogNotifMateri(lgm)){
			if("admin".equalsIgnoreCase(role)){
				if(notifMgr.insertNotifMateriTrainee() && notifMgr.insertNotifMateriTrainer()) {
					cek = true;
				}
			}
			else if("trainer".equalsIgnoreCase(role)){
				if(notifMgr.insertNotifMateriTrainee() && notifMgr.insertNotifMateriTrainer() && notifMgr.insertNotifMateriIndividu("super.admin")) {
					cek = true;
				}
			}
			
		}
		
		if(cek) System.out.println("Success Insert new Notification Materi");
		return cek;
	}

	private ScheduleForm setListSchedule(ScheduleForm scheduleForm, ScheduleManager scheduleManager, 
			FileManager filesharingManager, UserModel user, HttpServletRequest request) {	
		//Set list of Schedule
		List tmpListSch = scheduleManager.getAllSchedule(user.getUserid(), user.getRole(), scheduleForm.getSelectedBatchId(), scheduleForm.getCurrentPage());
		List result = new ArrayList();
		
		if(tmpListSch != null) {
			for (int i = 0; i < tmpListSch.size(); i++) {
				ScheduleModel sm = (ScheduleModel) tmpListSch.get(i);
				sm.setListFileSch(setIsFileExistLst(filesharingManager.selectFileSch(sm.getBatchClassId())));
				result.add(sm);
			}
		}
		
		scheduleForm.setRole(user.getRole());
		scheduleForm.setTotalPage(scheduleManager.getTotalPage(user.getUserid(), user.getRole(), scheduleForm.getSelectedBatchId()));
		scheduleForm.setListSchedule(result);
		request.setAttribute("listSchedule", scheduleForm.getListSchedule());
		
		return scheduleForm;
	}
	
	private List setIsFileExistLst(List tmpLst){
		List result = new ArrayList();
		if(tmpLst != null) {
			int size = tmpLst.size();
			for(int i=0; i<size; i++) {
				FileModel tmpFileMod = (FileModel) tmpLst.get(i);
				String filePath = getServlet().getServletContext().getRealPath("/") +tmpFileMod.getFilePath();
				File fileToCreate = new File(filePath, tmpFileMod.getFileName());
				
				if(!fileToCreate.exists()){ // File is not exist
					tmpFileMod.setIsFileExist(false);
				} else {
					tmpFileMod.setIsFileExist(true);
				}
				result.add(tmpFileMod);
			}
		}

		return result;
		}
}
